package com.uduemc.biso.node.web.api.ueditor.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.core.property.uploadpro.UploadImage;
import com.uduemc.biso.core.property.uploadpro.base.UploadBaseValid;
import com.uduemc.biso.core.property.uploadpro.base.UploadBaseValidSize;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.core.utils.RepertorySrcUtil;
import com.uduemc.biso.node.web.api.pojo.ResponseRepertory;
import com.uduemc.biso.node.web.api.service.RepertoryService;
import com.uduemc.biso.node.web.api.service.UploadService;
import com.uduemc.biso.node.web.api.service.hostsetup.HSUploadSizeService;
import com.uduemc.biso.node.web.api.ueditor.pojo.UeditorConfig;

@Controller
@RequestMapping("/api/ueditor")
public class UeditorUploadController {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private UploadService uploadServiceImpl;

	@Autowired
	private RepertoryService repertoryServiceImpl;

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private HSUploadSizeService hSUploadSizeServiceImpl;

	@GetMapping("/upload/config")
	public void config(HttpServletResponse response) {
		// 获取配置信息
		actionConfig(response);
	}

	@PostMapping("/upload/uploadimage")
	public void uploadimage(@RequestPart(value = "file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (file.isEmpty()) {
			logger.info("未能获取到上传的文件");
			actionResponseData(response, JsonResult.illegal());
			return;
		}
		// 验证上传的文件是否符合要求
		JsonResult validFile = uploadServiceImpl.validFile(file);
		if (validFile != null) {
			logger.info("上传文件不符合要求");
			String originalFilename = file.getOriginalFilename();
			String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
			long allowSzieByExt = globalProperties.getUpload().getAllowSzieByExt(ext);
			long size = file.getSize();
			// 是否是过大
			if (allowSzieByExt < size) {
				Map<String, Object> result = new HashMap<>();
				UploadImage uploadImage = globalProperties.getUpload().getInfos().getImage();
				UploadBaseValid valid = uploadImage.getValid();
				UploadBaseValidSize validSize = valid.getSize();
				result.put("state", validSize.getMessage());
				actionResponseData(response, result);
				return;
			}
			actionResponseData(response, JsonResult.illegal());
			return;
		}

		HRepertory hRepertory = uploadServiceImpl.nodeUploadHandler(file, 0L);
		if (hRepertory == null) {
			actionResponseData(response, JsonResult.assistance());
			return;
		}

		// 制作符合富文本需要的返回数据
		Map<String, Object> result = new HashMap<>();
		result.put("state", "SUCCESS");
		result.put("url", RepertorySrcUtil.getNodeImageSrcByRepertory(hRepertory));
		result.put("title", hRepertory.getOriginalFilename());
		result.put("original", hRepertory.getOriginalFilename());
		actionResponseData(response, result);
	}

	// /upload/listimage?start=0&size=20&noCache=1548846216014
	@GetMapping("/upload/listimage")
	public void listimage(@RequestParam("start") int start, @RequestParam("size") int pageSize, HttpServletResponse response) throws Exception {
		int page = 0;
		if (start == 0) {
			page = 1;
		} else {
			page = (int) Math.ceil((double) start / (double) pageSize) + 1;
		}
		ResponseRepertory responseRepertory = new ResponseRepertory();
		responseRepertory.setLabelId(-1L).setPage(page).setSize(pageSize).setType(new short[] { 0, 4 }).setOriginalFilename("");
		PageInfo<HRepertory> data = repertoryServiceImpl.getCurrentAndResponseRepertory(responseRepertory);

		// 制作符合富文本需要的返回数据
		Map<String, Object> result = new HashMap<>();
		result.put("state", "SUCCESS");
		result.put("start", start);

		List<Map<String, Object>> list = new ArrayList<>();
		for (HRepertory hRepertory : data.getList()) {
			Map<String, Object> item = new HashMap<>();
			item.put("url", RepertorySrcUtil.getNodeImageSrcByRepertory(hRepertory));
			item.put("title", hRepertory.getOriginalFilename());
			item.put("original", hRepertory.getOriginalFilename());
			list.add(item);
		}
		result.put("list", list);
		result.put("total", data.getTotal());
		actionResponseData(response, result);
	}

	@PostMapping("/upload/uploadvideo")
	@ResponseBody
	public JsonResult uploadvideo(@RequestPart(value = "file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (file.isEmpty()) {
			return JsonResult.illegal();
		}
		// 验证上传的文件是否符合要求
		JsonResult validFile = uploadServiceImpl.validFile(file);
		if (validFile != null) {
			logger.info("上传视频文件不符合要求 validFile: " + validFile.toString());
			return validFile;
		}

		HRepertory hRepertory = uploadServiceImpl.nodeUploadHandler(file, 0L);
		if (hRepertory == null) {
			return JsonResult.assistance();
		}

		return JsonResult.ok(1);
	}

	@GetMapping("/upload/listvideo")
	public void listvideo(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "size", required = false, defaultValue = "12") int pageSize, HttpServletResponse response) throws Exception {
		ResponseRepertory responseRepertory = new ResponseRepertory();
		responseRepertory.setLabelId(-1L).setPage(page).setSize(pageSize).setType(new short[] { 5 }).setOriginalFilename("");
		PageInfo<HRepertory> data = repertoryServiceImpl.getCurrentAndResponseRepertory(responseRepertory);

		// 制作符合富文本需要的返回数据
		Map<String, Object> result = new HashMap<>();
		result.put("state", "SUCCESS");
		result.put("start", page);

		List<Map<String, Object>> list = new ArrayList<>();
		for (HRepertory hRepertory : data.getList()) {
			Map<String, Object> item = new HashMap<>();
			item.put("repertoryid", hRepertory.getId());
			item.put("url", RepertorySrcUtil.getNodeVideoSrcByHostIdAndId(hRepertory));
			item.put("title", hRepertory.getOriginalFilename());
			item.put("original", hRepertory.getOriginalFilename());
			list.add(item);
		}
		result.put("list", list);
		result.put("size", pageSize);
		result.put("total", data.getTotal());
		actionResponseData(response, result);
	}

	private void actionResponseData(HttpServletResponse response, Object data) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=utf-8");

		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(objectMapper.writeValueAsString(data));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	// 获取配置信息
	private void actionConfig(HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");

		UeditorConfig config = new UeditorConfig();

		long uploadSize = hSUploadSizeServiceImpl.uploadSize((short) 0);
		config.setImageMaxSize(uploadSize);

		uploadSize = hSUploadSizeServiceImpl.uploadSize((short) 1);
		config.setFileMaxSize(uploadSize);

		uploadSize = hSUploadSizeServiceImpl.uploadSize((short) 5);
		config.setVideoMaxSize(uploadSize);

		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(objectMapper.writeValueAsString(config));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

}
